<template>
  <div class="user_settings">
    <h1 class="title item">个人信息</h1>
    <div class="user_avatar item">
      <div class="head">头像</div>
      <div class="avatar_box">
        <div class="avatar">
          <img :src="user.avatar" alt />
        </div>
        <div class="upload_box">
          <span class="tips">图片大小不超过5M</span>
          <Upload
            :action="action"
            :data="{token: token}"
            :before-upload="handleBeforeUpload"
            :on-success="handleSuccess"
            :on-error="handleError"
            :disabled="disabled"
            :show-upload-list="false"
          >
            <Button type="primary" long>点击上传</Button>
          </Upload>
        </div>
      </div>
    </div>
    <div class="user_username item">
      <div class="head">用户名</div>
      <div class="input_box">
        <input type="text" class="ipt" v-model="user.username" placeholder="填写用户名" />
      </div>
    </div>
    <div class="user_email item">
      <div class="head">邮箱</div>
      <div class="input_box">
        <input type="text" class="ipt" v-model="user.email" placeholder="填写邮箱" />
      </div>
    </div>
    <div class="user_introduction item">
      <div class="head">个人简介</div>
      <div class="input_box">
        <input type="text" class="ipt" v-model="user.introduction" placeholder="填写个人简介" />
      </div>
    </div>
    <div class="item">
      <div class="head"></div>
      <Button type="primary" @click="submitInfo()">提交</Button>
    </div>
  </div>
</template>

<script>
import jwt_decode from "jwt-decode";
import { mapState } from "vuex";
export default {
  name: "UserSettings",
  data() {
    return {
      action: "https://upload-z2.qiniup.com",
      token: "",
      disabled: false,
      loading: false
    };
  },
  computed: {
    ...mapState({
      user: state => state.user
    })
  },

  methods: {
    //上传前的钩子
    async handleBeforeUpload() {
      await this.$axios
        .post("/qntoken")
        .then(res => {
          this.token = res.data.data;
        })
        .catch(err => {
          console.log(err);
        });
      // 禁止再次点击上传
      this.disabled = !this.disabled;
    },
    //上传成功后的钩子
    handleSuccess(res) {
      console.log(res);
      let myid = this.user.uid;
      this.$axios
        .post("/updateAvatar", {
          avatar: "http://" + res.fileUrl,
          uid: myid
        })
        .then(res => {
          if (res.data.code == "0") {
            const auth = res.data.data;
            localStorage.setItem("auth", auth);
            // 解析token
            const decode = jwt_decode(auth);
            this.$store.dispatch("setIsAuthenticated", true);
            this.$store.dispatch("setUser", decode);
            this.$Message.success({
              background: true,
              content: "更新成功",
              duration: 2.5
            });
          } else {
            this.$Message.error({
              background: true,
              content: res.data.msg,
              duration: 2.5
            });
          }
        })
        .catch(err => {
          this.$Message.error({
            background: true,
            content: "上传失败",
            duration: 2.5
          });
        });
    },
    //上传失败后的钩子
    handleError(err) {
      this.$Message.error({
        content: "上传失败，请重试",
        background: true,
        duration: 3
      });
    },

    //提交信息
    submitInfo() {
      if (!this.loading) {
        this.loading = true;
        this.$axios
          .post("/updateUserInfo", {
            uid: this.user.uid,
            username: this.user.username,
            email: this.user.email,
            introduction: this.user.introduction,
            avatar: this.user.avatar,
            createDate: this.user.createDate
          })
          .then(res => {
            this.loading = false;
            if (res.data.code == "0") {
              const auth = res.data.data;
              localStorage.setItem("auth", auth);
              // 解析token
              const decode = jwt_decode(auth);
              this.$store.dispatch("setIsAuthenticated", true);
              this.$store.dispatch("setUser", decode);
              this.$Message.success({
                background: true,
                content: "更新成功",
                duration: 2.5
              });
            } else {
              this.$Message.error({
                background: true,
                content: res.data.msg,
                duration: 2.5
              });
            }
          })
          .catch(err => {
            this.loading = false;
            this.$Message.error({
              background: true,
              content: err.response.data.error[0].message,
              duration: 2.5
            });
            console.log(err.response);
          });
      } else {
        return;
      }
    }
  },
  mounted() {}
};
</script>

<style lang='scss'>
.user_settings {
  max-width: 960px;
  margin: 0 auto;
  background-color: #fff;
  margin-top: 1.5rem;
  padding: 3rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
  .item {
    border-bottom: 1px solid #ddd;
    padding: 1.5rem 0;
    display: flex;
    flex-direction: row;
    align-items: center;
    .input_box {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      flex: 1;
      .ipt {
        flex: 1;
        height: 2rem;
        font-size: 1.1rem;
        color: #b6b6b6;
        border: none;
        outline: none;
        padding-right: 2rem;
      }

      .ivu-btn,
      .ivu-btn:focus {
        border: none !important;
        box-shadow: none;
        span {
          letter-spacing: 2px !important;
          color: #007fff;
        }
      }
    }
  }
  .head {
    min-width: 5rem;
    font-size: 0.9rem;
  }
  .user_avatar {
    display: flex;
    flex-direction: row;
    .avatar_box {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: flex-start;
      flex: 1;
      .avatar {
        height: 5rem;
        width: 5rem;
        background-color: #ddd;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .upload_box {
        display: flex;
        flex-direction: column;
        justify-content: center;
        margin-left: 2rem;
        .tips {
          font-size: 14px;
          color: #b3b3b3;
        }
        .ivu-upload-select {
          display: block;
          .ivu-btn {
            margin-top: 0.5rem;
          }
        }
      }
    }
  }
  .user_username {
  }
}
@media screen and (max-width: 400px) {
  .ipt {
    max-width: 10rem;
    padding-right: 0;
  }
  .user_settings .user_avatar .avatar_box .avatar {
    width: 4rem;
    height: 4rem;
  }
  .user_settings .user_avatar .avatar_box .upload_box {
    margin-left: 1rem;
    max-width: 6rem;
  }
}
</style>